import { ref } from 'vue'
class Audio extends EventTarget{
    constructor() {
        super();
        this.audio = document.querySelector('#player');
        this.audio.volume = 1;
        this.duration = ref(0)
        this.currentTime = ref(0)
        this.progress = ref(0)
        this.isPlaying = ref(false)
        this.audio.addEventListener('canplay', (e) => {
            this.play()
            this.isPlaying.value = true
            this.duration.value = this.audio.duration
        });
        this.audio.addEventListener('error', (e) => {
            console.log(e)
            // this.dispatchEvent(new CustomEvent('error', {
            //     detail: {
            //         message: '播放失败',
            //         song: this.audio.src
            //     }
            // }))
        });
        this.audio.addEventListener('timeupdate', (e) => {
            this.currentTime.value = this.audio.currentTime
            this.progress.value = Math.floor(this.audio.currentTime / this.audio.duration * 100) || 0
        })
        this.audio.addEventListener('ended', (e) => {
            this.pause()
            this.isPlaying.value = false
            this.dispatchEvent(new CustomEvent('ended'))

        });
    }

    time(s) {
        // return s ? Math.floor(s / 60) + ':' + ('0' + Math.floor(s % 60)).slice(-2) : '00:00';
        return  Math.floor(s / 60) + ':' + ('0' + Math.floor(s % 60)).slice(-2)
    }

    durationMin() {
        this.duration.value = this.time(this.duration.value)
    }

    async startPlay(song){
        this.audio.src = song.audio_url;
    }

    play(){
        this.audio.play();
        this.isPlaying.value = true
    }

    pause(){
        this.audio.pause();
        this.isPlaying.value = false
    }

    playing(){
        if(this.isPlaying.value){
            this.pause()
        }else{
            this.play()
        }
    }

    seek(progress){
        this.audio.currentTime = this.audio.duration * progress;
    }

    loop(bool) {
        this.audio.loop = bool;
    }

    volume(value){
        this.audio.volume = value;
    }
}

let audio = new Audio();

export default audio;